﻿using Quartz;
using Quartz.Impl;
using Quartz.Spi;

namespace AdminSystem.Application
{
    public class QuartzDemoService : IQuartzDemoService
    {
        private readonly IJobFactory jobFactory;

        public QuartzDemoService(IJobFactory jobFactory)
        {
            this.jobFactory = jobFactory;
        }

        public async Task Run()
        {
            var schedulerFactory = new StdSchedulerFactory();
            // 获取调度器
            IScheduler sched = await schedulerFactory.GetScheduler();


            // 定义作业 - 向 Redis 中写入当前时间
            var jobDetail = JobBuilder.Create<MyJob>()
                .WithIdentity("job1", "group1")
                .Build();

            // 定义触发器 - 每隔3秒执行一次，共执行5次
            var trigger = TriggerBuilder.Create()
                .WithIdentity("trigger1", "group1")
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(3).WithRepeatCount(1))
                .StartNow()
                .Build();

            sched.JobFactory = jobFactory;

            // 将作业和触发器添加到调度器
            await sched.ScheduleJob(jobDetail, trigger);

            // 启动调度器
            await sched.Start();
        }
    }
}
